package buco.jsonrpc;

import java.io.IOException;
import java.io.Writer;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;

import buco.core.api.*;

public class BundleWireConverter implements JSONStreamAware {

	private BundleWire wire; 
	
	public BundleWireConverter(BundleWire wire) {
		this.wire = wire; 
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void writeJSONString(Writer wr) throws IOException {
		JSONObject jsonWire = new JSONObject();
		JSONArray requirements = new JSONArray();
		JSONArray capabilities = new JSONArray();
		
		int fromID = wire.getFrom().getBundleID();
		int toID = wire.getTo().getBundleID();
		jsonWire.put("from", fromID);
		jsonWire.put("to", toID);
		jsonWire.put("isActive", wire.isWireActive());
		
		// Add Requirements
		for(Requirement req: wire.getRequirements()) {
			requirements.add(new RequirementConverter(req)); 
		}	
		
		// Add Capabilities 
		for(Capability cap : wire.getCapabilities()) {
			capabilities.add(new CapabilityConverter(cap)); 
		}
		
		jsonWire.put("requirements", requirements);
		jsonWire.put("capabilities", capabilities); 
		
		jsonWire.writeJSONString(wr);  		
	}

}
